"""Add tags and workflow tags tables

Revision ID: 3bc0a0970817
Revises: da03a0dfa2db
Create Date: 2024-12-23 00:34:49.841129

"""

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "3bc0a0970817"
down_revision: str | None = "da03a0dfa2db"
branch_labels: Sequence[str] | None = None
depends_on: Sequence[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "tag",
        sa.Column("surrogate_id", sa.Integer(), nullable=False),
        sa.Column(
            "created_at",
            sa.TIMESTAMP(timezone=True),
            server_default=sa.text("(now() AT TIME ZONE 'utc'::text)"),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.TIMESTAMP(timezone=True),
            server_default=sa.text("(now() AT TIME ZONE 'utc'::text)"),
            nullable=False,
        ),
        sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("owner_id", sa.UUID(), nullable=True),
        sa.Column("name", sa.String(), nullable=False),
        sa.Column("color", sa.String(), nullable=True),
        sa.ForeignKeyConstraint(
            ["owner_id"],
            ["workspace.id"],
            ondelete="CASCADE",
            name="tag_owner_id_fkey",
        ),
        sa.PrimaryKeyConstraint("surrogate_id", name="tag_pkey"),
        sa.UniqueConstraint("name", "owner_id", name="tag_name_owner_id_key"),
    )
    op.create_index(op.f("ix_tag_id"), "tag", ["id"], unique=True)
    op.create_index(op.f("ix_tag_name"), "tag", ["name"], unique=False)
    op.create_table(
        "workflowtag",
        sa.Column("tag_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("workflow_id", sa.String(), nullable=False),
        sa.ForeignKeyConstraint(
            ["tag_id"],
            ["tag.id"],
            name="workflowtag_tag_id_fkey",
        ),
        sa.ForeignKeyConstraint(
            ["workflow_id"],
            ["workflow.id"],
            name="workflowtag_workflow_id_fkey",
        ),
        sa.PrimaryKeyConstraint("tag_id", "workflow_id", name="workflowtag_pkey"),
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("workflowtag")
    op.drop_index(op.f("ix_tag_name"), table_name="tag")
    op.drop_index(op.f("ix_tag_id"), table_name="tag")
    op.drop_table("tag")
    # ### end Alembic commands ###
